const express = require('express')
const joi = require('joi')
// 创建应用实例
const app = express()

// 导入body-parser
const bodyParser = require('body-parser')
// 当extended为false，值为数组或字符串/true时，值为任意类型
app.use(bodyParser.urlencoded({ extended: false }))
// 处理json格式数据
app.use(bodyParser.json())
// 全局挂载错误中间件
app.use((req, res, next) => {
    // status=0为成功,status=1为失败
    res.cc = (err, status = 1) => {
        res.send({
            status,
            // 判断这个err是错误对象还是字符串？
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

// 导入cors中间件
const cors = require('cors')
// 全局挂载
app.use(cors())

// 导入multer,用于上传文件
const multer = require('multer')
// 在upload文件夹里存放图片
const upload = multer({ dest: './public/upload' })
// 使用中间件
app.use(upload.any())
// 设置静态资源文件夹，静态托管
app.use(express.static('./public'))

// 导入jwt密钥
const jwtconfig = require('./jwt_config/index')
const { expressjwt: jwt } = require('express-jwt')
// app.use(jwt({
//     secret: jwtconfig.jwtSecretKey,
//     algorithms: ['HS256']
// }).unless({
//     path: [/^\/api\//]
// }))

// 路由模块 
const loginRouter = require('./router/login')
const Joi = require('joi')
app.use('/api', loginRouter)//挂载登录路由
const userinfoRouter = require('./router/userinfo')
app.use('/user', userinfoRouter)//挂载用户信息路由
const settingRouter = require('./router/setting')
app.use('/setting', settingRouter)//挂载系统设置路由
const productRouter = require('./router/product')
app.use('/product', productRouter)//挂载产品信息路由
const messageRouter = require('./router/message')
app.use('/message', messageRouter)//挂载消息管理路由
const fileRouter = require('./router/file')
app.use('/file', fileRouter)//挂载合同管理路由
const logRouter = require('./router/log')
app.use('/log', logRouter)//挂载登录日志和操作日志路由
const overviewRouter = require('./router/overview')
app.use('/overview', overviewRouter)//挂载系统概览页面路由
const departmentMsgRouter = require('./router/department_msg')
app.use('/departmentMsg', departmentMsgRouter)//挂载部门消息路由
// 对不符合joi情况的规则进行报错
app.use((err, req, res, next) => {
    if (err instanceof Joi.ValidationError) return res.cc('输入的数据不符合joi验证规则')
})

// 绑定和侦听指定端口
app.listen(3007, () => {
    console.log('http://127.0.0.1:3007')
})